<?php
require_once 'Char.php';
/**
 * Player class, holds user data, retrieve db info and save it too.
 * @package char
 * @author alcaitiff
 */
class Player extends Char
{
	protected $commands=array(), $id=null;
    /**
     *
     * @param string $user
     * @param string $char
     */
	function __construct ($user=null,$char=null){
		$this->id=$user;
		if($char==null and $user!=null){
			$char=$this->retrieveFirstChar();
		}elseif($char!=null and $user!=null and !$this->haveChar($char,$user)){
			$char=null;
		}	
		parent::__construct($char);
	}

    /**
     *
     * @param int $tick
     */
	public function refresh($tick){
		parent::refresh($tick);
		$this->retrieveCommands();
	}
	
    //***********************************************************************************************************
    //					DATABASE METHODS
    //***********************************************************************************************************
	/**
     * Retrieve player commands
     * @return void
     */
	private function retrieveCommands(){
		if($this->id!=null){
			if($this->setRefresh(0)){
				MessageSystem::addDebugMessage('Retrieving player '.$this->charId.' commands');
				$dbo=new DB();
				$db=$dbo->db;
				$stmt = $db->prepare(	'SELECT commands.command,commands.description '.
										'FROM commands,command_roles,characters_roles '.
										'WHERE ( '.
											'characters_roles.`char_id` = ? and '.
											'command_roles.role = characters_roles.role and '.
											'commands.command = command_roles.command and '.
											'command_roles.level <= characters_roles.level )'
										);
				$stmt->bind_param("s", $this->charId);
				$stmt->execute();
				$stmt->bind_result($command,$description);
				while($stmt->fetch()){
					$this->commands[$command]=$description;
				}
				$stmt->close(); 
			}
		}else{
			MessageSystem::addDebugMessage('Null id player have no commands');
		}

	}
    /**
     * Retrieve the first char name
     * @return string
     */
	private function retrieveFirstChar(){
		$dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare(	'SELECT `char_id` FROM `char`  '.
								'WHERE user = ? '.
								'LIMIT 1'
								);
	    $stmt->bind_param("s", $this->id);
	    $stmt->bind_result($char);
	    $stmt->execute();
	    $stmt->fetch();
  		$stmt->close(); 
		return $char;
	}
    /**
     * Verify if $user have $char
     * @param string $char Character name
     * @param string $user User name
     * @return boolean
     */
	private function haveChar($char,$user=null){
		if($user==null){
			$user=$this->charId;
		}
		$dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare(	'SELECT `char_id` FROM `char`  '.
								'WHERE (`user` = ? and `char_id` = ?)'.
								'LIMIT 1'
								);
	    $stmt->bind_param("ss", $user,$char);
	    $stmt->bind_result($char);
	    $stmt->execute();
	    if($stmt->fetch()){
	    	$ret=true;
	    }else{
    	    $ret=false;
	    }
  		$stmt->close(); 
		return $ret;
	}
}